/**
 * 
 */
package gps.io.readers.file;

import java.io.File;
import java.text.SimpleDateFormat;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import gps.model.Match;
import gps.model.Point;

/**
 * @author Pablo
 * 
 */
public class MatchFileReader {

	private Match match;

	public MatchFileReader(String fileName) {
		// TODO read the file gpx whis the coordinates of the track ç
		// and waypoints and initialize match variable with the results
		 SimpleDateFormat format = new SimpleDateFormat(
                 "yyyy-MM-dd'T'HH:mm:ss'Z'");
		 match = new Match();
		try {
			File fXmlFile = new File(this.getClass().getClassLoader().getResource(fileName).getPath());
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);

			NodeList wayPoints = doc.getElementsByTagName("wpt");

			for (int i = 0; i < wayPoints.getLength(); i++) {
				Point point = new Point();
				Node nNode = wayPoints.item(i);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					point.setLatitude(Double.parseDouble(eElement.getAttribute("lat")));
					point.setLongitude(Double.parseDouble(eElement.getAttribute("lon")));
					point.setTimestamp(format.parse( eElement.getElementsByTagName("time").item(0).getTextContent()).getTime());
					match.getWayPoints().add(point);
				}
			}
			
			//TODO refactor this in more method, it is exactly the same code...
			
			
			NodeList trackPoints = doc.getElementsByTagName("trkpt");
			for (int i = 0; i < trackPoints.getLength(); i++) {
				Point point = new Point();
				Node nNode = trackPoints.item(i);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					point.setLatitude(Double.parseDouble(eElement.getAttribute("lat")));
					point.setLongitude(Double.parseDouble(eElement.getAttribute("lon")));
					point.setTimestamp(format.parse( eElement.getElementsByTagName("time").item(0).getTextContent()).getTime());
					match.getTrackPoints().add(point);
				}
			}
			
		} catch (Exception e) {
			System.out.println("SOMETHING WRONG");
		}
	}

	public Match getMatch() {
		return match;
	}

}
